<?php

namespace App\Providers;

use Cache;
use App\Models\Category;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 将Carbon的时间设置为中文
        \Carbon\Carbon::setLocale('zh');

        \App\Models\User::observe(\App\Observers\UserObserver::class);
        \App\Models\Reply::observe(\App\Observers\ReplyObserver::class);
        \App\Models\Topic::observe(\App\Observers\TopicObserver::class);
        \App\Models\Link::observe(\App\Observers\LinkObserver::class);
        \App\Models\Category::observe(\App\Observers\CategoryObserver::class);

        /**
         * 顶部菜单
         */
        view()->composer('layouts._header', function ($view) {
            // 这里的菜单是随意写的，可以根据实际情况去获取，比如从数据库中     $menus = ['主页','文章'];
            $cache_key = env("cache_category_key");
            $cache_expire_in_minutes = 1440;
            $categories = Cache::remember($cache_key, $cache_expire_in_minutes , function () {
                return Category::orderBy('sort', 'asc')->get();
            });
            $categories = json_decode($categories);
            $view->with('categories', $categories);
        });

        // 记录所使用的sql语句
        \DB::listen(function ($query) {
            $sql = $query->sql;
            $bindings = $query->bindings;
            $time = $query->time;
            \Log::debug(var_export(compact('sql', 'bindings', 'time'), true));
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if (env('APP_DEBUG')) {
            $this->app->register('VIACreative\SudoSu\ServiceProvider');
        }
    }
}
